import React , {useEffect} from 'react';
import { Modal, Form, Input } from 'antd';
import { FormInstance } from 'antd/lib/form';
import { TableListItem } from '../data.d';

interface RenameFormProps {
  modalVisible: boolean;
  onCancel: () => void;
  onSubmit: (values: TableListItem) => void;
  values: TableListItem;
}

const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 16 },
};

const formRef = React.createRef<FormInstance>();

// 获取文件名
const getFileName = (name:string) => {
  return name.substring(0, name.lastIndexOf("."))
}
// 获取 .后缀名
const getExtension = (name:string) => {
  return name.substring(name.lastIndexOf("."))
}

const RenameForm: React.FC<RenameFormProps> = (props) => {
  const { modalVisible, onSubmit, onCancel, values } = props;
  const [form] = Form.useForm();

  const handleFinish = (values: { [key: string]: any }) => {
    if (onSubmit) {
      onSubmit(values as TableListItem);
    }
  };

  const handleUpdate = () => {
    if (!form) return;
    form.submit();
  };

  const modalFooter = { okText: '保存', onOk: handleUpdate, onCancel };

  useEffect(() => {
    if(modalVisible){
      if(values && values.id){
        form.setFieldsValue({
          id: values.id,
          code: values.code,
          name: getFileName(values.filename),
          extension:getExtension(values.filename),
        });
      }else{
        form.resetFields();
      }
    }
    
  },[modalVisible]);

  const renderContent = () => {
    return (
      <>
        <Form.Item name="id" style={{ display: 'none' }}></Form.Item>
        <Form.Item name="code" style={{ display: 'none' }}></Form.Item>
        <Form.Item
          name="name"
          label="素材名称"
          rules={[{ required: true, max: 64, whitespace: true }]}
        >
          <Input placeholder="请输入素材名称" />
        </Form.Item>
      </>
    );
  };
  return (
    <Modal destroyOnClose title="重命名" visible={modalVisible} {...modalFooter}>
      <Form {...layout} ref={formRef} form={form} name="renameForm" onFinish={handleFinish}>
        {renderContent()}
      </Form>
    </Modal>
  );
};

export default RenameForm;
